<?php
include_once APPPATH . "libraries/Listdetail_Controller.php";

class Rights extends Listdetail_Controller
{

    public function __construct()
    {
        parent::__construct();
        $this->deletemode = 'DEL';
        $this->idmode = 'UUID';   // 表关键字模式  ID 为自增量类型， UUID 为guid模式
        $this->load->model("public/Common_tools","tools");
    }

    /*
     *  提供列表页,明细页的下拉框数据准备
     */
    protected function _getGlobalData($data)
    {
        $data = parent::_getGlobalData($data);
        if (($this->url_method === 'view') || ($this->url_method === 'edit')) {
            $sql_getBtnDefine = "select s.id,s.name,s.icon,s.btnDefine,r.btnrights,s.project_name,s.bg_color,s.description,r.uriid from sys_conf s ";
            $sql_getBtnDefine .= " left outer join sys_rights r on s.id=r.uriid and r.userid='" . $data['keyId'] . "' where s.src_url <> 'default' order by s.id";
            $btnDefine = $this->mydb->find($sql_getBtnDefine);
            $btnName = $this->dball->getConfData("按钮名称");
            for ($i = 0; $i < sizeof($btnDefine["obj"]); $i++) {
                $btnDefine["obj"][$i]["btnDefine"] = $this->tools->arrayreplace($btnDefine["obj"][$i]["btnDefine"], $btnName, "name", "value");
                $btnDefine["obj"][$i]["btnrights"] = $this->tools->arrayreplace($btnDefine["obj"][$i]["btnrights"], $btnName, "name", "value");
            }
            $data['datalist'] = $btnDefine['obj']; //按钮信息
            $getProjectSql = "SELECT DISTINCT project_name AS projectName FROM sys_conf WHERE project_name IS NOT NULL AND project_name !='' GROUP BY project_name";
            $selectProject = $this->mydb->find($getProjectSql);
            $data['projects'] = $selectProject['obj'];
            $sql = "SELECT id,rolename as name from sys_roles";
            $types = $this->mydb->find($sql);
            $data['types'] = $types['obj'];
        }
        return $data;
    }

    public function addRole()
    {
        $roleId = $_POST["type"];
        $userId = $_POST["userid"];
        $userRightsSql = "select uriid,btnrights from sys_rights where userid = '$userId'";
        $userRights = $this->mydb->find($userRightsSql);
        $roleRightsSql = "select uriid,btnrights from sys_rolerights where rolesid='$roleId'";
        $roleRights = $this->mydb->find($roleRightsSql);
        $rights = array();
        foreach ($userRights["obj"] as $right) {
            if (isset($rights[$right["uriid"]])) {
                $btnrights = array();
                $old = $rights[$right["uriid"]];
                if (null != $old && "" != $old) {
                    $old = explode(",", $old);
                    foreach ($old as $btnright) {
                        if (!in_array($btnright, $btnrights))
                            $btnrights[] = $btnright;
                    }
                }
                $new = $right["btnrights"];
                if (null != $new && "" != $new) {
                    $new = explode(",", $new);
                    foreach ($new as $btnright) {
                        if (!in_array($btnright, $btnrights))
                            $btnrights[] = $btnright;
                    }
                }
                $rights[$right["uriid"]] = implode(",", $btnrights);
            } else {
                $rights[$right["uriid"]] = $right["btnrights"];
            }
        }

        foreach ($roleRights["obj"] as $right) {
            if (isset($rights[$right["uriid"]])) {
                $btnrights = array();
                $old = $rights[$right["uriid"]];
                if (null != $old && "" != $old) {
                    $old = explode(",", $old);
                    foreach ($old as $btnright) {
                        if (!in_array($btnright, $btnrights))
                            $btnrights[] = $btnright;
                    }
                }
                $new = $right["btnrights"];
                if (null != $new && "" != $new) {
                    $new = explode(",", $new);
                    foreach ($new as $btnright) {
                        if (!in_array($btnright, $btnrights))
                            $btnrights[] = $btnright;
                    }
                }
                $rights[$right["uriid"]] = implode(",", $btnrights);
            } else {
                $rights[$right["uriid"]] = $right["btnrights"];
            }
        }
        $this->mydb->db->trans_start();
        $this->mydb->db->delete('sys_rights', array('userid' => $userId));
        $this->mydb->db->trans_complete();
        $this->load->helper('guid_helper');
        foreach ($rights as $key => $right) {
            $uridata = array();
            $uridata["Id"] = guid();
            $uridata["userid"] = $userId;
            $uridata["uriid"] = $key;
            $uridata["btnrights"] = $right;
            $uridata["createuser"] = $this->session->userdata['sessioninfo']['userId'];
            $uridata["createdatetime"] = date('Y-m-d G:i:s');
            $this->mydb->setTable("sys_rights");
            $this->mydb->setKeyId("Id");
            $this->mydb->addData($uridata);
        }
        echo $this->url_module . '/' . $this->url_model;
    }


    /*
 * 在数据操作(create,update,delete)前,切换页面前调用
 * type = create,update,delete
 */
    protected function _beforeDBAct($type, $result)
    {
        log_message('debug', '_beforeDBAct()->type : ' . print_r($type, true));
        if ($type === 'edit') {
            $this->mydb->db->delete('sys_rights', array('userid' => $result[$this->griddefine['keyid']]));
            $uri = array();
            $uridata = array();
            foreach ($_POST as $key => $value) {  //提取所有uri checked的项目
                $ll = explode('_', $key);
                if (sizeof($ll) == 2) {
                    $this->load->helper('guid_helper');
                    $uridata["Id"] = guid();
                    $uridata["userid"] = $result['id'];
                    $uridata["uriid"] = $ll[1];
                    $uridata["btnrights"] = "";
                    $uridata["createuser"] = $this->session->userdata['sessioninfo']['userId'];
                    $uridata["createdatetime"] = date('Y-m-d G:i:s');
                    $uri[$ll[1]] = $uridata;
                }
            }
            foreach ($_POST as $key => $value) {  //为每个uri checked的项目处理各个btn
                $ll = explode('_', $key);
                if (sizeof($ll) == 3) {
                    if (isset($uri[$ll[1]]))
                        $uri[$ll[1]]["btnrights"] .= "," . $ll[2];
                }
            }
            $btndata = $this->dball->getConfData("按钮名称");
            foreach ($uri as $arr) {
                $arr["btnrights"] = $this->tools->arrayreplace($arr["btnrights"], $btndata, "value", "name");
                $this->mydb->setTable("sys_rights");
                $this->mydb->setKeyId("Id");
                $this->mydb->addData($arr);
            }
            $result = array();
        }
        log_message('debug', '_beforeDBAct()->params : ' . print_r($result, true));
        return $result;
    }

}
